import { API } from '@/constants/api';
import { portal as submitUpdateModal } from 'src/components/cooperation/submitUpdate/submitUpdateModal.vue';
import { portal as saveLoading } from 'src/components/Project/modals/SaveLoading.vue';
import { treeForEach } from "src/util/common";
import { SysMLUtilHelper, MofModelRepositoryHelper } from "src/api/sysml-imports";
import { LocalFileService } from 'src/util/localFile/LocalFileService';
import updateModel from "src/components/cooperation/submitUpdate/UpdateModel";
import { createError, errorCode } from 'src/constants/ErrorConfig';

class SubmitUpdate {
  openSubmitUpdateModal() {
    submitUpdateModal
      .popup()
      .then((res) => {
        this.submitProjects(res);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  submitProjects(comment) {
    saveLoading.popup({
      time: 2,
      msg: '正在提交更改到CoWork服务器',
      saveFn: () => {}
    });
    let checkOutIds = [];
    console.log('-app.activeProject.metadata.sysml.model----', app.activeProject.metadata.sysml.model);
    treeForEach([app.activeProject.metadata.sysml.model], (node) => {
      if ((node.getTypeName() === 'Package' || node.getTypeName() === 'Model' || node.getTypeName() === 'Profile') && node.status !== 5) {
        checkOutIds.push({ packageId: node.id, flag: node.status });
      }
    });
    const blob = SysMLUtilHelper.saveProject(app.activeProject.config.id, SysMLUtilHelper.toArrayList(Array(app.activeProject.metadata.sysml.model.model)));
    let param = {
      comment: comment,
      project: {
        config: app.activeProject.config,
        onlineConfig: app.activeProject.onlineConfig,
        model: blob,
      },
      checkOutIds: checkOutIds,
    };
    console.log("param", param);
    app.$post(API.PLATFORM_SERVICE_PROJECT_SUBMIT, param)
      .then((res) => {
        const project = res.data;
        project.config.projectFullPath = app.activeProject.config.projectFullPath; //// 修复协同提交更改后，本地项目列表不正确的问题
        //// 提交更改成功
        app.activeProject && (app.activeProject.onlineConfig.needSubmit = false);
        this.updateModel(project);
        LocalFileService.writeFile(window.$ele.path.resolve(project.config.projectPath, project.config.projectName + (project.config.online ? '.md3t' : '.md3') ), JSON.stringify(project));
        //// updateModel.updateProject();
      })
      .catch((err) => {
        //// createError(errorCode.SUBMIT_ERROR);
        app.$messageBox.error({
          text: '提交失败',
          duration: 10
        });
      });
  }
  async updateModel(project){
    await this.deleteProject(project.config.id);
    LocalFileService.loadProjectData(JSON.stringify(project)).then((res) => {
      LocalFileService.switchToProject(res);
      app.$messageBox.success({ text: '更新成功' });
      app.$bus.emit('project-modified');
      app.activeProject.onlineConfig.needSubmit = false;
    });
  }
  deleteProject(projectId) {
    app.proxy.projects.delete(projectId);
    //// SysMLUtilHelper.removePoolById(projectId);
    MofModelRepositoryHelper.removePool(projectId);
  }
  async mergeErr(){
    await  app.$Confirm.popup({
      title: '提交',
      content: '云端提交失败',
      subContent: '请尝试更新协同项目，是否更新？',
      showCheckbox: false,
      status: 'warn',
      cancelText: '取消',
      okText: '立即更新',
    })
      .then((res) => {
        //// TODO 更新
      })
      .catch((e) => {
        e && console.error(e);
      });
  }
}
const submitUpdate = new SubmitUpdate();
export default submitUpdate;
